﻿#pragma once
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QString>


#include "LogClass/logger.h"


////封装对文件,以及json的读写
namespace XuanCommon{

///
/// \brief readFile 读取文件
/// \param path 路径
/// \param content 返回读取的内容
/// \return 是否读取成功
///
[[maybe_unused]]
static bool readFile(const QString &path,QByteArray &content){
    QFile file(path);
    if(!file.open(QFile::ReadOnly)){
        LOG_WARN<<"打开(读取)"<<path<<"文件失败!";
        return false;
    }
    content = file.readAll();
    file.close();
    return true;
}



////
/// readJson 读取json操作
/// json是含有键值对的列表,qt提供QJsonDocument读取json文档
[[maybe_unused]]
static bool readJson(const QByteArray &data ,QJsonDocument &doc){
    QJsonParseError error;
    doc  = QJsonDocument::fromJson(data,&error);
    if(doc.isNull()){
        LOG_WARN<<"读取json失败! :"<<error.errorString();
        return false;
    }
    return true;
}
//读取数组
[[maybe_unused]]
static bool readJson(const QByteArray &data, QJsonArray &arr){
    QJsonDocument doc;
    bool isOk = readJson(data,doc);
    if(isOk){
        arr = doc.array();
    }
    return isOk;
}
//读取对象
[[maybe_unused]]
static bool readJson(const QByteArray &data,QJsonObject &obj){
    QJsonDocument doc;
    bool isOk =readJson(data,doc);
    if(isOk){
        qDebug()<<"读取json转对象成功!";
        obj=  doc.object();
    }
    return isOk;
}

///readJsonFile读取json位置
[[maybe_unused]]
static bool readJsonFile(const QString &filePath,QJsonDocument &jsonDoc){
    QByteArray data;
    if(!readFile(filePath,data)){
        return false;
    }
    return readJson(data,jsonDoc);
}
[[maybe_unused]]
static bool readJsonFile(const QString &filePath,QJsonArray & jsonArr){
    QByteArray data;
    if(!readFile(filePath,data)){
        return false;
    }
    return readJson(data,jsonArr);
}
[[maybe_unused]]
static bool readJsonFile(const QString & filePath,QJsonObject &jsonObj){
    QByteArray data;
    qDebug()<<"读取json数据成功";
    if(false ==readFile(filePath,data)){
        return false;
    }
    auto res = readJson(data,jsonObj);
    return res;
}

///
/// \brief WriteFile 写入文件操作
/// \param filePath 路径
/// \param content 内容
/// \return
///
[[maybe_unused]]
static bool writeFile(const QString & filePath,const QByteArray & content){
    QFile file(filePath);
    if(!file.open(QFile::WriteOnly)){
        LOG_WARN<<"文件(写入)"<<filePath<<"打开失败!";
        return false;
    }
    file.write(content);
    file.close();
    return true;
}
[[maybe_unused]]
static bool writeJsonFile(const QString & filePath,const QJsonDocument &jsonDoc){
    return writeFile(filePath,jsonDoc.toJson());
}
[[maybe_unused]]
static bool writeJsonFile(const QString & filePath,const QJsonArray & jsonArr){
    return writeJsonFile(filePath,QJsonDocument(jsonArr));
}
[[maybe_unused]]
static bool writeJsonFile(const QString & filePath,const QJsonObject &jsonObj){
    return writeJsonFile(filePath,QJsonDocument(jsonObj));
}



}







